package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImp implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 历史订单查询
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuertUser(int page, int pageSize, Integer status) {
        //开启分页查询
        PageHelper.startPage( page,pageSize );
        //条件查询订单信息
        Long userId = BaseContext.getCurrentId();
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId( userId );
        ordersPageQueryDTO.setStatus( status );
        //满足条件的分页查询结果
        Page<Orders> pageQuery =  orderMapper.pageQuery(ordersPageQueryDTO);
        //查询订单详细信息
        List<OrderVO> list = new ArrayList<>();
        if(pageQuery != null && pageQuery.size() > 0) {
            pageQuery.forEach( p -> {
                //获取订单详细信息
                List<OrderDetail> detailList =  orderDetailMapper.getByOrderId(p.getId());
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties( p,orderVO );
                orderVO.setOrderDetailList( detailList );
                list.add(orderVO);
            } );
        }

        return new PageResult(pageQuery.getTotal(),list);//total records
    }

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //处理业务异常（地址簿为空，购物车为空）

        //地址簿为空
        AddressBook addressBook = addressBookMapper.getById( ordersSubmitDTO.getAddressBookId() );
        if(addressBook == null) {
            throw new AddressBookBusinessException( MessageConstant.ADDRESS_BOOK_IS_NULL );
        }
        //购物车为空
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId( userId );
        List<ShoppingCart> list = shoppingCartMapper.list( shoppingCart );
        if(list == null || list.size() ==0) {
            throw new ShoppingCartBusinessException( MessageConstant.SHOPPING_CART_IS_NULL );
        }
        //将数据分别插入到订单表和订单明细表中

        //将一条数据插入到订单表
        Orders orders = new Orders();
        BeanUtils.copyProperties( ordersSubmitDTO,orders );
        orders.setUserId( userId );
        orders.setOrderTime( LocalDateTime.now() );
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus( Orders.UN_PAID );
        orders.setPhone( addressBook.getPhone() );
        orders.setConsignee( addressBook.getConsignee() );
        orders.setNumber( String.valueOf( System.currentTimeMillis() ) );
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail() );

        orderMapper.insert(orders);
        //插入n条数据到订单明细表
        List<OrderDetail> orderDetailList = new ArrayList<>();
        list.forEach( shoppingCart1 -> {
            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties( shoppingCart1,detail );
            detail.setOrderId( orders.getId() );
            orderDetailList.add(detail);
        } );
        orderDetailMapper.insertBatch(orderDetailList);
        //清空购物车
        shoppingCartMapper.delete( shoppingCart );
        //封装VO
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderTime( orders.getOrderTime() )//下单时间
                .orderAmount( orders.getAmount() )//总金额，前段计算以后返回给后端，购物车中的菜品金额加上餐具费以及固定的配送费
                .orderNumber( orders.getNumber() )//订单编号
                .id( orders.getId() )//订单号
                .build();
        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
//    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        //原始代码
////        // 当前登录用户id
////        Long userId = BaseContext.getCurrentId();
////        User user = userMapper.getById(userId);
////
////        //调用微信支付接口，生成预支付交易单
////        JSONObject jsonObject = weChatPayUtil.pay(
////                ordersPaymentDTO.getOrderNumber(), //商户订单号
////                new BigDecimal(0.01), //支付金额，单位 元
////                "苍穹外卖订单", //商品描述
////                user.getOpenid() //微信用户的openid
////        );
////
////        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
////            throw new OrderBusinessException("该订单已支付");
////        }
////
////        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
////        vo.setPackageStr(jsonObject.getString("package"));
//
//        //方法一
//        OrderPaymentVO vo = new OrderPaymentVO();
//        vo.setNonceStr("666");
//        vo.setPaySign("hhh");
//        vo.setPackageStr("prepay_id=wx");
//        vo.setSignType("RSA");
//        vo.setTimeStamp("1670380960");
//        return vo;
//
//
//
//    }
    //方法二
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
//    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
////        //调用微信支付接口，生成预支付交易单
////        JSONObject jsonObject = weChatPayUtil.pay(
////                ordersPaymentDTO.getOrderNumber(), //商户订单号
////                new BigDecimal(0.01), //支付金额，单位 元
////                "苍穹外卖订单", //商品描述
////                user.getOpenid() //微信用户的openid
////        );
////
////        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
////            throw new OrderBusinessException("该订单已支付");
////        }
//
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("code", "ORDERPAID");
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        // 替代微信支付成功后的数据库订单状态更新，直接在这里更新了
//        // 根据订单号查询当前用户的该订单
//        Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);
//
//        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
//        Orders orders=new Orders();
//        orders.setId(ordersDB.getId());
//        orders.setStatus(Orders.TO_BE_CONFIRMED);
//        orders.setPayStatus(Orders.PAID);
//        orders.setCheckoutTime(LocalDateTime.now());
////        Orders orders = Orders.builder()
////                .id(ordersDB.getId())
////                .status(Orders.TO_BE_CONFIRMED) // 订单状态，待接单
////                .payStatus(Orders.PAID) // 支付状态，已支付
////                .checkoutTime(LocalDateTime.now()) // 更新支付时间
////                .build();
//
//        orderMapper.update(orders);
//
//        return vo;
//    }

//方法二修改后完成接单催单提醒
public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
    // 当前登录用户id
    Long userId = BaseContext.getCurrentId();
    User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("code", "ORDERPAID");

    OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
    vo.setPackageStr(jsonObject.getString("package"));

    // 根据订单号查询当前用户的该订单
    Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);

    paySuccess(ordersDB.getNumber());

    return vo;
}



    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        //通过webSocket向客户端浏览器推送信息
        Map map = new HashMap();
        map.put( "type",1 );
        map.put( "orderId",ordersDB.getId() );
        map.put( "content","订单号"+outTradeNo );

        String json = JSON.toJSONString( map );
        webSocketServer.sendToAllClient( json );
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    public OrderVO getById(Long id) {
        //select * from order_detail where order_id = id
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId( id );
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties( orders,orderVO );
        orderVO.setOrderDetailList( orderDetailList );
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    public void cancelUser(Long id) {
        //三种情况 待付款待派单（直接取消,待派单需要退回钱） 派送中已接单（电话沟通，相当于取消失败 返回信息） 其他(取消失败)
        Orders orders = orderMapper.getById( id );
        //异常情况：订单不存在
        if(orders == null) {
            throw new OrderBusinessException( MessageConstant.ORDER_NOT_FOUND );
        }
        //后两种情况
        if(orders.getStatus() > 2) {
            throw new OrderBusinessException( MessageConstant.ORDER_STATUS_ERROR );
        }
        //待派单情况下需要退回钱
        Orders orders1 = new Orders();
        orders1.setId( id );
        if(orders.getStatus() == Orders.TO_BE_CONFIRMED) {
            //修改支付状态为退钱
            orders1.setPayStatus( Orders.REFUND );
        }
        orders1.setStatus( Orders.CANCELLED );
        orders1.setCancelReason("用户取消" );
        orders1.setCancelTime( LocalDateTime.now() );
        orderMapper.update( orders1 );
    }

    /**
     * 再来一单
     * @param id
     */
    public void repetition(Long id) {
        //异常情况：判断订单是否存在
        Orders orders = orderMapper.getById( id );
        if(orders == null) {
            throw new OrderBusinessException( MessageConstant.ORDER_NOT_FOUND );
        }
        //插入购物车数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId( id );
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        Long userId = BaseContext.getCurrentId();
        orderDetailList.forEach( orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties( orderDetail,shoppingCart,"id" );//两个都有id,并且都是主键（自增），所以不能复制
            shoppingCart.setCreateTime( LocalDateTime.now() );
            shoppingCart.setUserId( userId );
            shoppingCartList.add( shoppingCart );
        } );
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 搜索订单
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult pageQueryAdmin(OrdersPageQueryDTO ordersPageQueryDTO) {
        //开启分页查询
        PageHelper.startPage( ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize() );
//        Long userId = BaseContext.getCurrentId();
//        ordersPageQueryDTO.setUserId( userId );
        Page<Orders> pageQuery = orderMapper.pageQuery( ordersPageQueryDTO );//分页条件查询获得数据
        //部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(pageQuery);
        return new PageResult(pageQuery.getTotal(),orderVOList);
    }

    /**
     * 查询各个状态的订单数量
     *
     * @return
     */
    public OrderStatisticsVO getStatisticsByUserId() {
        //查询全部 待接单2 待派送3 派送中4 已完成5 已取消6
        Integer confirmed =  orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliverInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer toBeConfirmed = orderMapper.countStatus( Orders.TO_BE_CONFIRMED );
        OrderStatisticsVO order = new OrderStatisticsVO();
        order.setConfirmed( confirmed );
        order.setToBeConfirmed( toBeConfirmed );
        order.setDeliveryInProgress( deliverInProgress );

        return order;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder().id(ordersConfirmDTO.getId()).status( Orders.CONFIRMED ).build();

        orderMapper.update( orders );
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //先判断是否是待接单状态 是：修改状态为已取消 不是：不能修改
        Long orderId = ordersRejectionDTO.getId();
        Orders orders = orderMapper.getById( orderId );
        // 订单只有存在且状态为2（待接单）才可以拒单
        if(orders == null || !orders.getStatus().equals( Orders.TO_BE_CONFIRMED )) {
            throw  new OrderBusinessException( MessageConstant.ORDER_NOT_FOUND );
        }
        //待接单状态以后判断订单是否已经支付，假如已经支付需要退钱，修改支付状态为退钱
        if(orders.getPayStatus().equals( Orders.PAID )) {
            orders.setPayStatus( Orders.REFUND );
        }
        //并且要写入拒单原因
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    public void cancelAdmin(OrdersCancelDTO ordersCancelDTO) {
        //判断订单状态是否为待接单和待派送 修改订单状态为已取消 用户假如付款了需要退款 指定取消原因
        Orders orders = orderMapper.getById( ordersCancelDTO.getId() );
        if(orders.getStatus().equals( Orders.TO_BE_CONFIRMED ) || orders.getStatus() .equals( Orders.CONFIRMED)) {
            if(orders.getPayStatus().equals( Orders.PAID )) {
                orders.setPayStatus( Orders.REFUND );
            }
            orders.setCancelReason( ordersCancelDTO.getCancelReason() );
            orders.setCancelTime( LocalDateTime.now() );
            orders.setStatus( Orders.CANCELLED );
            orderMapper.update( orders );
        }
    }

    /**
     * 派送订单
     * @param id
     */
    public void delivery(Long id) {
        //对订单状态为代派送的订单修改为派送中
        Orders orders = orderMapper.getById( id );
        if(orders == null || !orders.getStatus().equals( Orders.CONFIRMED )) {
            throw new OrderBusinessException( MessageConstant.ORDER_STATUS_ERROR );
        }
        orders.setStatus( Orders.DELIVERY_IN_PROGRESS );
        orderMapper.update( orders );
    }

    /**
     * 完成订单
     * @param id
     */
    public void complete(Long id) {
        Orders orders = orderMapper.getById( id );
        if(orders == null || !orders.getStatus().equals( Orders.DELIVERY_IN_PROGRESS )) {
            throw new OrderBusinessException( MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus( Orders.COMPLETED );
        orders.setDeliveryTime( LocalDateTime.now() );
        orderMapper.update( orders );
    }

    /**
     * 催单
     * @param id
     */
    public void reminder(Long id) {
        Orders orders = orderMapper.getById( id );
        if(orders == null) {
            throw  new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND );
        }
        Map map = new HashMap();
        map.put( "type",2 );
        map.put( "orderId",id );
        map.put( "content","订单号"+orders.getNumber() );

        webSocketServer.sendToAllClient( JSON.toJSONString( map ) );
    }


    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect( Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

}
